import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/my/sale_center/ai_pack_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/home/qkd_carousel_view.dart';
import 'package:sports_new/widgets/circular.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:sports_new/widgets/base/qkd_text.dart';
import '../../../entity/pay/ai_pack_entity.dart';
import '../../../utils/user.dart';
import '../../../widgets/check_widget.dart';
import '../../../widgets/base/qkd_image.dart';
import '../../../widgets/tip_widget.dart';

class AiPackPage extends StatefulWidget {
  const AiPackPage({super.key});

  @override
  State<AiPackPage> createState() => _AiPackPageState();
}

class _AiPackPageState extends State<AiPackPage>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<AiPackLogic>(
      init: AiPackLogic(),
      builder: (AiPackLogic logic) => MediaQuery.removePadding(
        context: context,
        removeTop: true,
        child: LoadingWidget<bool>(
          isLoading: logic.itemList.isEmpty,
          data: null,
          child: () => Container(
            color: Colours.white,
            child: Column(
              children: [
                Expanded(
                  child: Stack(
                    alignment: Alignment.bottomCenter,
                    children: [
                      GestureDetector(
                        onTap: () {
                          if (logic.animateValue == 1) {
                            logic.animate();
                          }
                        },
                        child: ScrollConfiguration(
                          behavior: const ScrollBehavior()
                              .copyWith(overscroll: false),
                          child: ListView(
                              controller: logic.scrollController,
                              children: [
                                if (logic.carousel.hasValue)
                                  QkdCarouselView(
                                    carousels: logic.carousel!,
                                    padding: 8,
                                    needTitle: false,
                                    aspectRatio: 359 / 120,
                                    needDot: (logic.carousel?.length ?? 0) > 1,
                                  ).paddingSymmetric(vertical: 8),
                                Row(
                                  children: [
                                    const QkdText("开通模型组合",
                                        fontSize: 16,
                                        fontWeight: FontWeight.w500),
                                    const Spacer(),
                                    QkdButton(
                                      width: 52,
                                      height: 24,
                                      onPressed: logic.setChoiceAll,
                                      text: "全选",
                                      textStyle: const TextStyle(fontSize: 12),
                                      strutStyle:
                                          Styles.centerStyle(fontSize: 12),
                                      borderRadius: 28,
                                      foregroundColor: logic
                                                  .choices[logic.index]
                                                  .length ==
                                              logic.itemList[logic.index].length
                                          ? Colours.grey99
                                          : Colours.white,
                                      borderSide: logic.choices[logic.index]
                                                  .length ==
                                              logic.itemList[logic.index].length
                                          ? const BorderSide(
                                              color: Colours.greyCC, width: 0.5)
                                          : BorderSide.none,
                                      backgroundColor: logic
                                                  .choices[logic.index]
                                                  .length ==
                                              logic.itemList[logic.index].length
                                          ? Colours.greyF7
                                          : Colours.main,
                                    )
                                  ],
                                ).paddingOnly(top: 8, left: 16, right: 16),
                                GridView.count(
                                  physics: const NeverScrollableScrollPhysics(),
                                  shrinkWrap: true,
                                  crossAxisCount: 3,
                                  padding:
                                      const EdgeInsets.fromLTRB(16, 13, 16, 0),
                                  crossAxisSpacing: 12,
                                  mainAxisSpacing: 12,
                                  childAspectRatio: 106 / 125,
                                  children: List.generate(
                                      logic.itemList[logic.index].length,
                                      (index) => item(
                                          logic.itemList[logic.index][index])),
                                ),
                                Container(height: 16),
                                const QkdText("模型组合规则",
                                        fontSize: 12,
                                        fontWeight: FontWeight.w500,
                                        color: Colours.grey66)
                                    .paddingSymmetric(horizontal: 16),
                                Container(height: 8),
                                const TipWidget(type: "ai_pack")
                                    .paddingSymmetric(horizontal: 16),
                                Container(height: 40)
                              ]),
                        ),
                      ),
                      chooseTime(),
                    ],
                  ),
                ),
                if (logic.noticeText.hasValue && logic.animateValue == 0)
                  Container(
                      alignment: Alignment.center,
                      width: Get.width,
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      color: const Color(0xFFFCECEA),
                      child: QkdText(
                        logic.noticeText,
                        fontSize: 12,
                        color: Colours.main,
                        needCenter: true,
                      )),
                Opacity(
                    opacity: 1 - logic.animateValue,
                    child: const Divider(color: Colours.greyEE, height: 0.5)),
                payBar()
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget payBar() {
    return GetBuilder<AiPackLogic>(builder: (logic) {
      return Container(
        height: 56,
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Row(
          children: [
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    QkdText(
                        "${(logic.priceSum[logic.index] * logic.getDiscount(logic.index)).toStringAsFixed(1)}球币",
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                        color: Colours.main),
                    Opacity(
                      opacity: 1 - logic.animateValue,
                      child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: logic.animateValue == 0 ? logic.animate : null,
                        child: Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8),
                          child: Row(children: [
                            QkdText("${logic.days?[logic.index] ?? 0}天",
                                color: Colours.grey99),
                            Container(width: 2),
                            Image.asset(Utils.getImgPath('arrow_up.png'),
                                width: 14)
                          ]),
                        ),
                      ),
                    )
                  ],
                ),
                if (logic.getDiscount(logic.index) != 1)
                  QkdText(
                    "${logic.priceSum[logic.index].toStringAsFixed(1)}球币",
                    decoration: TextDecoration.lineThrough,
                    fontSize: 12,
                    color: Colours.grey99,
                  )
              ],
            ),
            const Spacer(),
            QkdButton(
              width: 120,
              height: 40,
              onPressed: () async {
                if (!User.isLogin) {
                  await User.needLogin(() => logic.getData());
                }
                logic.toPay();
              },
              text: "立即支付",
              textStyle: const TextStyle(fontSize: 16),
              strutStyle: Styles.centerStyle(fontSize: 16),
              borderRadius: 20,
              foregroundColor: Colours.white,
              backgroundColor: Colours.main
                  .withOpacity(logic.priceSum[logic.index] != 0 ? 1 : 0.4),
            )
          ],
        ),
      );
    });
  }

  Widget chooseTime() {
    return GetBuilder<AiPackLogic>(builder: (logic) {
      return Transform.scale(
        scaleY: logic.animateValue,
        alignment: Alignment.bottomCenter,
        child: Opacity(
          opacity: logic.animateValue,
          child: Container(
            decoration: BoxDecoration(
                color: Colours.white,
                borderRadius:
                    const BorderRadius.vertical(top: Radius.circular(12)),
                boxShadow: [
                  BoxShadow(
                      offset: const Offset(0, -6),
                      blurRadius: 6,
                      color: const Color(0xFF6C86A3).withOpacity(0.15))
                ]),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Opacity(
                  opacity: logic.animateValue,
                  child: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: logic.animate,
                    child: Row(
                      children: [
                        const QkdText("模型时长选择", fontWeight: FontWeight.w500),
                        Container(width: 2),
                        Image.asset(Utils.getImgPath('arrow_down.png'),
                            width: 14)
                      ],
                    ).paddingSymmetric(vertical: 12, horizontal: 16),
                  ),
                ),
                ScrollConfiguration(
                  behavior: const ScrollBehavior().copyWith(overscroll: false),
                  child: SingleChildScrollView(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 16, vertical: 1),
                      scrollDirection: Axis.horizontal,
                      child: Row(
                          children: List.generate(logic.days?.length ?? 0,
                                  (index) => price(index, logic.days![index]))
                              .insertEvery(Container(width: 7)))),
                )
              ],
            ),
          ),
        ),
      );
    });
  }

  Widget price(int index, int day) {
    return GetBuilder<AiPackLogic>(builder: (logic) {
      return GestureDetector(
        onTap: () => logic.index = index,
        child: Container(
          height: 132,
          width: 106,
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
              color: logic.index == index
                  ? Colours.main.withOpacity(0.05)
                  : Colours.white,
              border: Border.all(
                  color:
                      logic.index == index ? Colours.main : Colours.redFDD9D9,
                  width: logic.index == index ? 1 : 0.5,
                  strokeAlign: BorderSide.strokeAlignOutside),
              borderRadius: BorderRadius.circular(8)),
          child: Column(
            children: [
              Container(
                  width: Get.width,
                  height: 28,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      color: logic.index == index
                          ? Colours.main.withOpacity(0.2)
                          : Colours.redFFF4F4),
                  child: QkdText("$day天")),
              SizedBox(
                width: Get.width,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Container(height: 16),
                    Text.rich(TextSpan(
                        style: const TextStyle(
                            fontWeight: FontWeight.w500,
                            fontSize: 20,
                            color: Colours.redBD2929),
                        children: [
                          TextSpan(
                              text: (logic.priceSum[index] *
                                      logic.getDiscount(index))
                                  .toStringAsFixed(1)),
                          TextSpan(
                              text: "球币".changeUnit,
                              style: const TextStyle(fontSize: 12))
                        ])),
                    if (logic.getDiscount(index) != 1)
                      Container(
                          margin: const EdgeInsets.only(top: 10),
                          padding: const EdgeInsets.symmetric(
                              horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                              color: logic.index != index
                                  ? const Color(0xFFFFF4F4)
                                  : const Color(0xFFFEE7E7),
                              borderRadius: BorderRadius.circular(15)),
                          child: QkdText(
                              "${logic.priceSum[index].toStringAsFixed(1)}球币",
                              needCenter: true,
                              decoration: TextDecoration.lineThrough,
                              fontSize: 10,
                              color: Colours.grey66))
                  ],
                ),
              )
            ],
          ),
        ),
      );
    });
  }

  Widget item(AiPackItem? entity) {
    return GetBuilder<AiPackLogic>(builder: (logic) {
      return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () => logic.setChoice(entity),
        child: Circular(
            color: Colours.greyF7F9FC,
            width: 106,
            height: 125,
            radius: 8,
            child: Stack(
              alignment: Alignment.topRight,
              children: [
                SizedBox(
                  width: 106,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Column(
                        children: [
                          QkdImage(
                                  imageUrl: entity?.logo,
                                  width: 52,
                                  height: 52,
                                  shape: BoxShape.circle)
                              .paddingOnly(bottom: 12),
                          QkdText(entity?.name,
                                  fontSize: 12, fontWeight: FontWeight.w500)
                              .paddingOnly(bottom: 2)
                        ],
                      ),
                      QkdText("${entity?.price ?? ""}球币",
                          needCenter: true, color: Colours.main, fontSize: 11)
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 8, right: 8),
                  child: CheckWidget(
                    value: logic.choices[logic.index]
                        .any((element) => element.priceId == entity?.priceId),
                    size: 14,
                  ),
                )
              ],
            )),
      );
    });
  }

  @override
  bool get wantKeepAlive => true;
}
